package com.utils;


import android.graphics.Bitmap;
import android.os.Environment;
import android.os.SystemClock;
import android.support.test.uiautomator.UiDevice;
import android.support.test.uiautomator.UiObject;
import android.support.test.uiautomator.UiObjectNotFoundException;
import android.support.test.uiautomator.UiSelector;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

import static android.os.SystemClock.sleep;

/**
 * XINHAO_HAN TOOL
 */
public class UIUtils {

    public static boolean IS_LOG_XINHAO_HAN = false;

    public static void showLog(String msg) {
        if (UIUtils.IS_LOG_XINHAO_HAN) {
            ChatClient.msg("<YZF>{'header':'XINHAO_HAN:','" + msg + "'</YZF>");
        }
    }

    // 截取字符串
    private static ArrayList<ArrayList<String>> StringArr(String str) {

        char[] charArray = str.toCharArray();
        // 判断这个索引
        int i = 0;
        ArrayList<ArrayList<String>> arrAll = new ArrayList<>();

        while (true) {
            ArrayList<String> arr = new ArrayList<>();

            while (true) {
                try {

                    if ((charArray.length - 1) < i) {
                        break;
                    }
                    Integer.parseInt(charArray[i] + "");
                    arr.add(charArray[i] + "");
                    i++;
                } catch (Exception e) {

                    break;
                }

            }
            if (arr.size() != 0)
                arrAll.add(arr);

            ArrayList<String> arr1 = new ArrayList<>();

            while (true) {

                try {
                    Integer.parseInt(charArray[i] + "");
                    break;
                } catch (Exception e) {
                    if ((charArray.length) - 1 < i) {
                        break;
                    }
                    arr1.add(charArray[i] + "");
                    i++;
                }

            }
            if (arr1.size() != 0)
                arrAll.add(arr1);

            if ((charArray.length) - 1 < i) {
                return arrAll;
            }

        }

        // return arrAll;

    }


    public static void numAbc(String psd, NumAbcListener numAbcListener) throws InterruptedException {

        ArrayList<ArrayList<String>> arrayLists = StringArr(psd);
        for (int i = 0; i < arrayLists.size(); i++) {

            ArrayList<String> strings = arrayLists.get(i);
            //判断是字母开头的还是数字开头的
            try {
                int i1 = Integer.parseInt(strings.get(0));
                //数字开头的
                numAbcListener.num2abc(true, strings.toString());
            } catch (Exception e) {
                //字母开头的
                numAbcListener.num2abc(false, strings.toString());
            }
        }
    }

    public interface NumAbcListener {
        void num2abc(boolean isNum2abd, String pwd) throws InterruptedException;
    }

    public static String getZSCodeSms(String str) {


        String substring = str.substring(str.indexOf("千万别给！验证码") + 8, str.indexOf("千万别给！验证码") + 14);

        return substring;
    }

    public static String getPACodeSms(String str) {


        String substring = str.substring(str.indexOf("动态码") + 3, str.indexOf("动态码") + 9);

        return substring;
    }

    public static String getXYSms(String str) {

        String substring = str.substring(5, 11);


        return substring;
    }

    /**
     * 保存文件
     *
     * @param bm
     * @param fileName
     * @throws IOException
     */
    public static String saveFile(Bitmap bm, String fileName) throws IOException {
        String path = Environment.getExternalStorageDirectory() + "/xinhao/";
        File dirFile = new File(path);
        if (!dirFile.exists()) {
            dirFile.mkdir();
        }
        File myCaptureFile = new File(path + fileName);
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
        bm.compress(Bitmap.CompressFormat.JPEG, 80, bos);
        bos.flush();
        bos.close();

        return path;
    }

    /**
     * ROOT截屏
     */
    public static void rootRec(String filePath) {

        Process process = null;
        try {
            process = Runtime.getRuntime().exec("su");
            PrintStream outputStream = null;
            try {
                outputStream = new PrintStream(new BufferedOutputStream(process.getOutputStream(), 8192));
                outputStream.println("screencap -p " + filePath);
                outputStream.flush();
            } catch (Exception e) {

            } finally {
                if (outputStream != null) {
                    outputStream.close();
                }
            }
            process.waitFor();
        } catch (Exception e) {

        } finally {
            if (process != null) {
                process.destroy();
            }
        }

    }

    public static void unZip(File srcFile, String destDirPath) throws RuntimeException {

        long start = System.currentTimeMillis();

        // 判断源文件是否存在

        if (!srcFile.exists()) {

            throw new RuntimeException(srcFile.getPath() + "所指文件不存在");

        }

        // 开始解压

        ZipFile zipFile = null;

        try {

            zipFile = new ZipFile(srcFile);

            Enumeration<?> entries = zipFile.entries();

            while (entries.hasMoreElements()) {

                ZipEntry entry = (ZipEntry) entries.nextElement();

                System.out.println("解压" + entry.getName());

                // 如果是文件夹，就创建个文件夹

                if (entry.isDirectory()) {

                    String dirPath = destDirPath + "/" + entry.getName();

                    File dir = new File(dirPath);

                    dir.mkdirs();

                } else {

                    // 如果是文件，就先创建一个文件，然后用io流把内容copy过去

                    File targetFile = new File(destDirPath + "/" + entry.getName());

                    // 保证这个文件的父文件夹必须要存在

                    if (!targetFile.getParentFile().exists()) {

                        targetFile.getParentFile().mkdirs();

                    }

                    targetFile.createNewFile();

                    // 将压缩文件内容写入到这个文件中

                    InputStream is = zipFile.getInputStream(entry);

                    FileOutputStream fos = new FileOutputStream(targetFile);

                    int len;

                    byte[] buf = new byte[1024];

                    while ((len = is.read(buf)) != -1) {
                        fos.write(buf, 0, len);
                    }
                    // 关流顺序，先打开的后关闭

                    fos.close();

                    is.close();

                }

            }

            long end = System.currentTimeMillis();

            System.out.println("解压完成，耗时：" + (end - start) + " ms");

        } catch (Exception e) {

            throw new RuntimeException("unzip error from ZipUtils", e);

        } finally {

            if (zipFile != null) {

                try {

                    zipFile.close();

                } catch (IOException e) {

                    e.printStackTrace();

                }

            }

        }

    }

    /**
     * 启动银行APP前service获取权限
     * J7————————SM-C710F————————1080———————1920
     * S5————————Lenovo K520————————1080———————2016
     * K5Pro————————Lenovo L38041————————1080———————2016
     * S5Pro————————Lenovo L58041————————1080———————2012
     * Z5————————Lenovo L78011————————1080———————2102
     * 国美————————GOME 2017M27A————————1080———————2046
     *
     * @param mDevice
     */
    public static void initServicePermission(UiDevice mDevice) {
        try {
            ChatClient.begintime = System.currentTimeMillis();//开始时间
            while (true) {
                long nowtime1 = System.currentTimeMillis();
                if ((nowtime1 - ChatClient.begintime) > ChatClient.overtime_20) {
                    showMsg("无权限弹窗");
                    break;
                }
                if (android.os.Build.MODEL.contains("Lenovo L78011")) {//Z5逻辑
                    UiObject mBT_setting = mDevice.findObject(new UiSelector().resourceId("android:id/button1").text("去设置"));
                    if (mBT_setting.exists()) {
                        showMsg("设置服务权限");
                        mBT_setting.click();
                        SystemClock.sleep(ChatClient.overtime_2);
                    }
                    UiObject mBT_start = mDevice.findObject(new UiSelector().resourceId("com.android.settings:id/switch_widget").text("关闭"));
                    if (mBT_start.exists()) {
                        showMsg("开启显示通知");
                        mBT_start.click();
                        SystemClock.sleep(ChatClient.overtime_1);
                    }
                    UiObject mBT_close = mDevice.findObject(new UiSelector().resourceId("android:id/switch_widget").text("关闭"));
                    if (mBT_close.exists()) {
                        showMsg("开启覆盖勿扰");
                        mBT_close.click();
                        SystemClock.sleep(ChatClient.overtime_1);
                        break;
                    }
                } else if (android.os.Build.MODEL.contains("Lenovo L38041")) {//K5 Pro 逻辑
                    mDevice.click(880, 1200);
                    sleep(ChatClient.overtime_2);
                    UiObject mBT_start = mDevice.findObject(new UiSelector().resourceId("com.android.settings:id/switch_widget").text("关闭"));
                    if (mBT_start.exists()) {
                        showMsg("开启显示通知");
                        mBT_start.click();
                        SystemClock.sleep(ChatClient.overtime_1);
                    }
                    UiObject mBT_close = mDevice.findObject(new UiSelector().resourceId("android:id/switch_widget").text("关闭"));
                    if (mBT_close.exists()) {
                        showMsg("开启覆盖勿扰");
                        mBT_close.click();
                        SystemClock.sleep(ChatClient.overtime_1);
                        break;
                    }
                } else if (android.os.Build.MODEL.contains("Lenovo L58041")) {//S5 Pro 逻辑 1080----2102
                    mDevice.click(880, 1200);
                    sleep(ChatClient.overtime_2);
                    UiObject mBT_start = mDevice.findObject(new UiSelector().resourceId("com.android.settings:id/switch_widget").text("关闭"));
                    if (mBT_start.exists()) {
                        showMsg("开启显示通知");
                        mBT_start.click();
                        SystemClock.sleep(ChatClient.overtime_1);
                    }
                    UiObject mBT_close = mDevice.findObject(new UiSelector().resourceId("android:id/switch_widget").text("关闭"));
                    if (mBT_close.exists()) {
                        showMsg("开启覆盖勿扰");
                        mBT_close.click();
                        SystemClock.sleep(ChatClient.overtime_1);
                        break;
                    }
                } else {        //S5（K520），SM-C710F逻辑
                    mDevice.click(880, 1200);
                    sleep(ChatClient.overtime_2);
                    UiObject mBT_start = mDevice.findObject(new UiSelector().resourceId("com.android.settings:id/switch_widget").text("已启用车载模式"));
                    if (mBT_start.exists()) {
                        showMsg("开启显示通知");
                        mBT_start.click();
                        SystemClock.sleep(ChatClient.overtime_1);
                    }
                    UiObject mBT_close = mDevice.findObject(new UiSelector().resourceId("android:id/switch_widget").text("已启用车载模式"));
                    if (mBT_close.exists()) {
                        showMsg("开启覆盖勿扰");
                        mBT_close.click();
                        SystemClock.sleep(ChatClient.overtime_1);
                        break;
                    }
                }
            }
            mDevice.pressBack();
        } catch (UiObjectNotFoundException e) {
            e.printStackTrace();
        }
    }

    public static void showMsg(String msg) {
        LogToFile.showLog("===UIUtils===", msg);
    }
}
